package framework.webmvc.component;

import util.OSCheckAndConvert;

import java.io.File;
import java.net.URL;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * the class that deal with different View Files
 */
public class InchViewResolver {
    private final String DEFAULT_TEMPLATE_SUFFIX = ".html";

    //resolvers root
    private File templateRootDir;
    //map that have the name of the view and file of the view file
    private Map<String,File> viewMapping = new ConcurrentHashMap<String,File>();

    /**
     * Constructor with root path
     * @param templateRoot root path
     */
    public InchViewResolver(String templateRoot) {
        URL url = this.getClass().getClassLoader().getResource(templateRoot);
        String templateRootPath = OSCheckAndConvert.stringConvert(url.getFile());
        this.templateRootDir = new File(templateRootPath);
        mapViews();
    }

    /**
     * constructor with root file(folder)
     * @param templateRootDir
     */
    public InchViewResolver(File templateRootDir) {
        this.templateRootDir = templateRootDir;
        mapViews();
    }

    /**
     * map the view in the root folder
     */
    private void mapViews() {
        for(File file : templateRootDir.listFiles()) {
            if(file.isDirectory()) { continue; }
            String viewName = file.getName();
            if(viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX)){
                viewMapping.put(viewName,file);
            }
        }
    }

    /**
     * get the view instance by giving a name
     * @param viewName name of view
     * @param locale
     * @return instance of the given name view/ null if not found
     */
    public InchView getViewByName(String viewName, Locale locale) {
        if(viewName == null || viewName.trim().equals("")) { return null; }
        viewName = viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX) ? viewName : (viewName + DEFAULT_TEMPLATE_SUFFIX);
        if(viewMapping.containsKey(viewName)) {
            return new InchView(viewMapping.get(viewName));
        }
        return null;
    }


}
